const { app, BrowserWindow } = require("electron/main");

const { ipcMain } = require("electron");
const url = require("url");
const path = require("path");

// 存储所有的窗口实例对象
const winRef = [];
// 用来记录消息通道 记录窗口进程要注册的事件
const messageChannelRecord = {};

/**
 * 注册监听事件
 * @param {*} channel 要注册的监听事件名称
 * @param {*} webContentsId 窗口id
 */
function registerChannel(channel, webContentsId) {
  console.log(`1注册监听事件 名称:${channel}, 窗口id:${webContentsId}`);
  if (messageChannelRecord[channel] !== undefined) {
    // channel 已经被注册了
    // 判断当前窗口是否被注册了
    let alreadyRegister = false;
    for (let i = 0; i < messageChannelRecord[channel].length; i++) {
      if (messageChannelRecord[channel][i] === webContentsId) {
        alreadyRegister = true;
        break;
      }
    }
    if (!alreadyRegister) {
      messageChannelRecord[channel].push(webContentsId);
    }
  } else {
    messageChannelRecord[channel] = [webContentsId];
  }
  console.log(
    `2注册监听事件已经完毕，最新的messageChannelRecord是：${messageChannelRecord}`
  );
}

/**
 * 监听注册函数触发动作
 */
ipcMain.on("registerChannelEvent", (event, channel) => {
  // event 窗口实例对象
  // channel 监听频道名称
  try {
    registerChannel(channel, event.sender.id);
  } catch (e) {
    console.error(e);
  }
});

function getWebContentsIds(channel) {
  // console.log(
  //   "=====",
  //   messageChannelRecord,
  //   channel,
  //   messageChannelRecord[channel]
  // );
  return messageChannelRecord[channel] || [];
}

/**
 *
 * @param {*} webContentsIds 注册channel事件的窗口id的数组
 * @param {*} channel 注册channel事件名称
 * @param {*} data 要传递的数据
 */
function transText(webContentsIds, channel, data) {
  for (let i = 0; i < webContentsIds.length; i++) {
    for (let j = 0; j < winRef.length; j++) {
      if (winRef[j].webContents.id === webContentsIds[i]) {
        winRef[j].webContents.send(channel, data);
        break;
      }
    }
  }
}

ipcMain.on("transTextEvent", (event, channel, data) => {
  // 遍历messageChannelRecord
  try {
    console.log(
      `last-发送数据到渲染进程${getWebContentsIds(channel)},${channel},${data}`
    );
    transText(getWebContentsIds(channel), channel, data);
  } catch (e) {
    console.error(e);
  }
});

/**
 *
 * @param {*} url
 * @returns 创建的窗口实例
 */
const createWindow = (url) => {
  const win = new BrowserWindow({
    width: 400,
    height: 400,
    // 网络偏好设置
    webPreferences: {
      // 预加载
      nodeIntegration: true, // 允许在渲染进程（窗口）中使用node.js
      contextIsolation: false, // 关闭上下文隔离
    },
  });
  win.loadURL(url);
  win.webContents.openDevTools();
  return win;
};
// whenReady是一个生命周期方法，会在Electron初始化完成后调用
app.whenReady().then(() => {
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      // 创建窗口前拼接url
      const url1 = url.format({
        protocol: "file",
        pathname: path.join(__dirname, "window1/window1.html"),
      });
      const url2 = url.format({
        protocol: "file",
        pathname: path.join(__dirname, "window2/window2.html"),
      });
      winRef.push(createWindow(url2), createWindow(url1));
    }
  });
});
